#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <err.h>
#include <libmscommon/mscommon.h>
#include <libmscommon/mstime.h>
#include <libmscommon/msepoll.h>
#include <libmslog/mslog.h>
#include <libmsprotocol/msprotocol.h>

#include <srt/srt.h>

#define FLAG "SRTSERVER_SAMPLE"
static char * pouturl=ms_null;
void* srtserver_send(void* args)
{
	URLVal *purlval_srt=(URLVal *)args;

	URLVal urlval_udp;
	memset(&urlval_udp,0,sizeof(URLVal));
	urlval_udp.purl_ptl=msptc_api_matchByPtcindex(msptc_udp);
	ms_strcpy(urlval_udp.url_ctt.url, pouturl);
	urlval_udp.url_ctt.opt.udp.ifcIn="ens33";
	urlval_udp.url_ctt.opt.udp.ipIn="192.168.200.83";
	urlval_udp.url_ctt.flags|=FLAG_WRITE;
	if(urlval_udp.purl_ptl->url_open(&urlval_udp.url_ctt)<0){
		ms_errExit(-1, "Open in url failed");
	}
	
	char data[1316]={0};
	time_t EtimepInstant;
	time_t EtimepGL;
	while (1){
		int recvlen=srt_recvmsg(purlval_srt->url_ctt.fd,data,sizeof(data));
		if(recvlen>0){
			if (urlval_udp.purl_ptl->url_write(&urlval_udp.url_ctt, data , recvlen)<0){
				ms_error("udp url_write failed");
				break;
			}
		}
		if(purlval_srt->url_ctt.fd<0){
			break;
		}
		ms_usleep(50);
		if(mstime_api_counterAsyncSec(&EtimepInstant, 10)){
			//mssrt_bstatsInstant(purlval_srt->url_ctt.fd, ms_false);
		}
		if(mstime_api_counterAsyncSec(&EtimepGL, 60)){
			//mssrt_bstatsGL(purlval_srt->url_ctt.fd, ms_false);
		}
	}
	urlval_udp.purl_ptl->url_close(&urlval_udp.url_ctt);
	return NULL;
}
int main(int argc, char **argv)
{
	mslog_api_init( 54, ms_null,ms_null, ms_null);
	if(3!=argc){
		ms_error("usage:%s srtPort outurl(udp)",argv[0]);
		mslog_api_deinit();
		return -1;
	}
	ms_s32 srtPort=ms_atoi(argv[1]);
	pouturl=argv[2];
	msptc_api_init();
	msptc_api_register();
	
	URLVal urlval_srt;
	memset(&urlval_srt,0,sizeof(URLVal));
	urlval_srt.purl_ptl=msptc_api_matchByPtcindex(msptc_srt);
	ms_memset(&urlval_srt.url_ctt,0,sizeof(URLContext));

	ms_sprintfs(urlval_srt.url_ctt.url,"srt://127.0.0.1:%d?mode=listener",srtPort);
	
	urlval_srt.url_ctt.opt.srt.listen=1;
	if(urlval_srt.purl_ptl->url_open(&urlval_srt.url_ctt)<0){
		ms_errExit(-1, "Open in url failed");
	}
	char buf[2048]={0};
	int len=0;
	int recver=0;

	while(1){
		recver=urlval_srt.purl_ptl->priv_func.srt.accept(&urlval_srt.url_ctt);
		if(recver>0){
			ms_debug("accept success");
			pthread_t rcvthread;
			pthread_create(&rcvthread, NULL, srtserver_send, &urlval_srt);
			break;
		}
		ms_sleep(1);
	}	
	while(1){
		ms_sleep(10);
	}	
	urlval_srt.purl_ptl->url_close(&urlval_srt.url_ctt);
	msptc_api_deinit();
	mslog_api_deinit();
}
#undef MAIN_C

